package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.FaultDb;
import com.ruoyi.system.domain.FaultSummary;
import com.ruoyi.system.domain.KeyBasket;
import com.ruoyi.system.mapper.FaultDbMapper;
import com.ruoyi.system.mapper.FaultSummaryMapper;
import com.ruoyi.system.service.IExcelService;
import com.ruoyi.system.service.IFaultSummaryService;
import com.ruoyi.system.service.IKeyBasketService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * ExcelService业务层处理
 *
 * @author 蒼飞
 * @date 2023-11-27
 */
@Service
@RequiredArgsConstructor
public class ExcelServiceImpl implements IExcelService {

    private final FaultDbMapper faultDbMapper;
    private final FaultSummaryMapper faultSummaryMapper;

    private final IFaultSummaryService faultSummaryService;
    private final IKeyBasketService keyBasketService;



    /**
     * 上传故障数据库excel并处理
     *
     * @param fileInputStream
     * @return
     */
    @Override
    public Integer uploadDbExcel(FileInputStream fileInputStream) throws IOException {
        Workbook workbook = new XSSFWorkbook(fileInputStream);

        // 获取第一个工作表
        Sheet sheet = workbook.getSheetAt(0);

        // 创建DataFormatter对象来格式化单元格内容
        DataFormatter dataFormatter = new DataFormatter();

        List<FaultDb> faultDbList = new ArrayList<>();

        // 获取第一行（表头）信息，确定分组
        Row headerRow = sheet.getRow(0);
        int numColumns = headerRow.getLastCellNum();

        List<Integer> groupSizes = new ArrayList<>();
        List<Integer> groupStartIndices = new ArrayList<>();
        String currentGroup = null;  // 当前组名
        int currentColumn = 0;  // 当前列的索引

        // 识别每个组占多少列
        while (currentColumn < numColumns) {
            String cellValue = getCellValue(headerRow, currentColumn, dataFormatter);

            if (cellValue != null && !cellValue.trim().isEmpty()) {
                // 如果是组名，开始新的组
                currentGroup = cellValue;
                groupStartIndices.add(currentColumn);  // 记录当前组的起始列

                // 向右继续检查直到遇到空字符串或新的组名
                int groupSize = 1;  // 每组的初始列数
                currentColumn++;  // 移动到下一个列

                while (currentColumn < numColumns) {
                    String nextCellValue = getCellValue(headerRow, currentColumn, dataFormatter);
                    // 如果是当前组名，表示该组继续占列
                    if (nextCellValue != null && nextCellValue.trim().equals(currentGroup)) {
                        groupSize++;
                        currentColumn++;
                    } else {
                        break;
                    }
                }

                // 保存当前组的列数
                groupSizes.add(groupSize);
            } else {
                // 如果是空字符串，跳过
                currentColumn++;
            }
        }
        groupStartIndices.add(numColumns);
        // 根据groupStartIndices计算groupSizes
        for (int i = 0; i < groupStartIndices.size() - 1; i++) {
            int groupSize = groupStartIndices.get(i + 1) - groupStartIndices.get(i);
            groupSizes.set(i, groupSize);
        }

        // 从第二行开始读取数据
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            // 获取当前组的名称
            currentColumn = 0;
            for (int groupIndex = 0; groupIndex < groupSizes.size(); groupIndex++) {
                int groupSize = groupSizes.get(groupIndex);
                String faultValue = getCellValue(row, currentColumn, dataFormatter);

                // 如果组名存在并且当前组至少有一列非空数据
                if (faultValue != null && !faultValue.trim().isEmpty()) {
                    FaultDb faultDb = new FaultDb();
                    faultDb.setGroup("组" + (groupIndex + 1));  // 设置当前组名

                    // 为该组生成唯一的UUID，并为该组的每行使用相同的key
                    String key = UUID.randomUUID().toString().substring(0, 5);  // 生成一个5位的UUID
                    //在UUID结尾拼上组几
                    key += faultDb.getGroup();
                    faultDb.setKey(key);  // 设置唯一key

                    // 处理该组的所有列数据
                    StringBuilder faultBuilder = new StringBuilder();
                    boolean hasData = false;

                    for (int col = currentColumn; col < currentColumn + groupSize; col++) {
                        String cellData = getCellValue(row, col, dataFormatter);
                        if (cellData != null && !cellData.trim().isEmpty()) {
                            if (hasData) {
                                faultBuilder.append("^");
                            }
                            faultBuilder.append(cellData);
                            hasData = true;
                        }
                    }

                    // 将合并后的值写入fault
                    if (hasData) {
                        faultDb.setFault(faultBuilder.toString());
                    }

                    // 添加到结果列表
                    if (faultDb.getFault() != null && !faultDb.getFault().trim().isEmpty()) {
                        Date currentDate = new Date();
                        faultDb.setTime(currentDate);
                        faultDbList.add(faultDb);
                    }
                }

                // 更新当前列到下一组的起始列
                currentColumn += groupSize;
            }
        }

        workbook.close();  // 关闭工作簿
        return faultDbMapper.insertFaultDbBatch(faultDbList);
    }


    // 获取单元格的值，使用DataFormatter来转换为字符串
    public static String getCellValue(Row row, int columnIndex, DataFormatter dataFormatter) {
        Cell cell = row.getCell(columnIndex);
        return dataFormatter.formatCellValue(cell);  // 使用DataFormatter格式化并返回
    }


    /**
     * 上传故障
     *
     * @param fileInputStream
     * @return
     * @throws IOException
     */
    @Transactional
    @Override
    public Integer uploadSummaryExcel(FileInputStream fileInputStream) throws IOException {
        //创建故障集合 方便存入数据库
        List<FaultSummary> faults = new ArrayList<>();
        //读取流中的工作簿
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        //获取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //获取总行数
        int rowCount = sheet.getPhysicalNumberOfRows();
        int dateNum = 0;
        int orderNum = 1;
        int numberNum = 2;
        int detailNum = 3;
        int submitterNum = 4;
        int teamNum = 5;
        int processorNum = 6;
        int resultNum = 7;
        int pushTimeNum = 8;


        for (int rowNum = 0; rowNum < rowCount; rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            Cell cell = row.getCell(0);
            if (cell == null) {
                continue;
            }
            if (rowNum == 0) {
                for (int i = 0; i < 1000000000; i++) {
                    Cell first = row.getCell(i);
                    if (first == null) {
                        break;
                    }
                    //                    first.setCellType(CellType.STRING);
                    if (first.getStringCellValue().contains("日期")) {
                        dateNum = i;
                    } else if (first.getStringCellValue().contains("车次")) {
                        orderNum = i;
                    } else if (first.getStringCellValue().contains("车号")) {
                        numberNum = i;
                    } else if (first.getStringCellValue().contains("故障详情")) {
                        detailNum = i;
                    } else if (first.getStringCellValue().contains("提交人")) {
                        submitterNum = i;
                    } else if (first.getStringCellValue().contains("责任班组")) {
                        teamNum = i;
                    } else if (first.getStringCellValue().contains("处理人员")) {
                        processorNum = i;
                    } else if (first.getStringCellValue().contains("结果")) {
                        resultNum = i;
                    } else if (first.getStringCellValue().contains("推送时间")) {
                        pushTimeNum = i;
                    }
                }
                continue;
            }
            List<FaultSummary> faultSummaries = new ArrayList<>();
            //第一行有多少列
            FaultSummary faultSummary = new FaultSummary();
            Cell number = row.getCell(numberNum);
            if (number == null) {
                break;
            }

            if (number.getCellType() == CellType.STRING) {
                // 获取字符串值
                String cellValue = number.getStringCellValue().trim();
                // 判断是否有多个数字（根据空格分隔）
                if (cellValue.contains(" ")) {
                    // 如果有空格，表示是多个数字，将它们分割成数组
                    String[] numbers = cellValue.split("[\\s ,，。.]+");
                    for (String num : numbers) {
                        if (num.equals("")) {
                            continue;
                        }
                        // 处理每个数字并设置
                        FaultSummary faultSummary1 = new FaultSummary();

//                        if (num.equals(" 353789")){
//                            String s =  num.replaceAll("\\s+", "");
//                            String c = s;
//                            int b = 1;
//                        }
                        num = num.replaceAll("[\\u00A0]+", "");
                        faultSummary1.setNumber(Long.parseLong(num.trim()));
                        faultSummaries.add(faultSummary1);
                    }
                } else {
                    cellValue = cellValue.replaceAll("[^\\d]", "");
                    // 如果没有空格，表示是单个数字
                    if (cellValue.equals("")) {
                        int t = 1;
                    }
                    faultSummary.setNumber(Long.parseLong(cellValue));
                    faultSummaries.add(faultSummary);
                }
//                faultSummary.setNumber(Long.parseLong(number.getStringCellValue()));
            } else {
                // 如果是数字类型，直接处理
                faultSummary.setNumber((long) number.getNumericCellValue());
                faultSummaries.add(faultSummary);
            }

            if(faultSummaries.isEmpty()) {
                return 1;
            }

            for (FaultSummary faultSummary1 : faultSummaries) {
                Cell date = row.getCell(dateNum);
                date.setCellType(CellType.NUMERIC);
                if (date.getDateCellValue() == null) {
                    faultSummary1.setDate(new Date());
                } else {
                    faultSummary1.setDate(date.getDateCellValue());
                }


                Cell order = row.getCell(orderNum);
                if (order != null) {
                    if (order.getCellType() == CellType.NUMERIC) {
                        order.setCellType(CellType.STRING);
                        faultSummary1.setOrders(order.getStringCellValue());
                    } else {
                        faultSummary1.setOrders(order.getStringCellValue());
                    }
                }

                Cell detail = row.getCell(detailNum);
                if (detail != null) {
                    faultSummary1.setDetail(detail.getStringCellValue());
                }

                Cell submitter = row.getCell(submitterNum);
                if (submitter != null) {
                    faultSummary1.setSubmitter(submitter.getStringCellValue());
                }

                Cell team = row.getCell(teamNum);
                if (team != null) {
                    faultSummary1.setResponsibleTeam(team.getStringCellValue());
                }

                Cell processor = row.getCell(processorNum);
                if (processor != null) {
                    faultSummary1.setProcessor(processor.getStringCellValue());
                }

                Cell result = row.getCell(resultNum);
                if (result != null) {
                    faultSummary1.setResult(result.getStringCellValue());
                }

                Cell pushTime = row.getCell(pushTimeNum);
                if (pushTime != null) {
                    pushTime.setCellType(CellType.NUMERIC);
                    faultSummary1.setPushTime(pushTime.getDateCellValue());
                }

                faultSummary1.setIsRepeat(0);
                faultSummary1.setIsParent(0);
            }
//                Date currentDate = new Date();
//                faultSummary.setTime(currentDate);
//                faultSummary.setKey();
            faults.addAll(faultSummaries);
        }

        //获取故障数据库
        List<FaultDb> faultDbs = faultDbMapper.selectFaultDbList(new FaultDb());
        // ArrayList<FaultSummary> faultSummaries = new ArrayList<>();
        // 找keyBasket里面 获取里面所有的key怕新来的key有重复
        List<KeyBasket> keyBaskets = keyBasketService.selectKeyBasketList(new KeyBasket());
        List<String> keyStringList = new ArrayList<>();
        if(keyBaskets != null && keyBaskets.size() != 0) {
            for(KeyBasket k :keyBaskets) {
                keyStringList.add(k.getKey());
            }
        }
        // 最终插入数据库的
        List<KeyBasket> cha = new ArrayList<>();
        for (FaultSummary fault : faults) {
            fault.setIsParent(0);
            fault.setIsRepeat(0);
//           faultSummaries.add(faultSummaryService.matchingFault(fault, faultDbs));
            // 生成key
            FaultSummary faultSummary = faultSummaryService.matchingFault(fault, faultDbs);
            if (faultSummary.getNumber().toString().length() > 10) {
                String string = faultSummary.getNumber().toString();
            }

            // faultSummaryMapper.insertFaultSummary(faultSummary);

            // TODO 插入篮子组
            String key = faultSummary.getKey();
            if(!keyStringList.contains(key)) {
                KeyBasket keyBasket = new KeyBasket();
                keyBasket.setKey(key);;
                String basket = UUID.randomUUID().toString().substring(0, 6);
                keyBasket.setBasket(basket);
                cha.add(keyBasket);
            }
            // process表示当前故障的自己以及他的长辈类
            //List<String> process = process(faultSummary);
            //process.add(key);

            // 根据List里面去找用in去找是否已经有父类
            //List<KeyBasket> all = keyBasketService.selectKeyBasket(process);

            //String basket = UUID.randomUUID().toString().substring(0, 6);
//            List<KeyBasket> cha = new ArrayList<>();
//
//            if (all == null || all.isEmpty()) {
//                // 生成新的以及父类
//                process.stream().forEach(item -> {
//                    KeyBasket f = new KeyBasket();
//                    f.setBasket(basket);
//                    f.setKey(item);
//                    cha.add(f);
//                });
//                if (cha.size() != 0) {
//                    keyBasketService.insertBatch(cha);
//                }
//            } else {
//                List<String> allString = new ArrayList<>();
//                all.stream().forEach(item -> allString.add(item.getKey()));
//                // 获取一条的basket
//                // 去重处理
//                List<String> difference = getDifference(process, allString);
//                String basket1 = all.get(0).getBasket();
//                if (difference != null && difference.size() != 0) {
//                    difference.stream().forEach(item -> {
//                        KeyBasket f = new KeyBasket();
//                        f.setBasket(basket1);
//                        f.setKey(item);
//                        cha.add(f);
//                    });

//                }
//            }

//            String key1 = fault.getKey();
//            // 根据key来查询basket
//            KeyBasket keyBasket = keyBasketService.selectByKey(key1);
//            fault.setParentFlag(keyBasket.getBasket());
        }
        keyBasketService.insertBatch(cha);
//        return faultSummaryMapper.insertFaultSummaryBatch(faultSummaries);

        // 处理父类相同的情况
//        for (FaultSummary fault : faults) {
//            if (fault.getIsParent() != null && fault.getIsParent() != 1) {
//                for (FaultSummary fault1 : faults) {
//                    if (fault1 != fault && Objects.equals(fault.getNumber(), fault1.getNumber())) {
//                        if (Objects.equals(fault.getParentFlag(), fault1.getParentFlag())) {
//                            fault.setIsParent(1);
//                            fault1.setIsParent(1);
//                        }
//                    }
//                }
//            }
//        }

        // 处理重复故障了

        // 主逻辑：遍历faultSummaryList和当前的faultSummary进行匹配
        for (FaultSummary f1 : faults) {
            if (f1.getIsParent() == 0){
                //f1.setParentFlag(null);
            }
            for (FaultSummary fs1 : faults) {
                if (f1 != fs1 && Objects.equals(f1.getNumber(),fs1.getNumber())){
                    // 获取 faultSummary1 的 key，并将其分割
                    String[] faultSummaryDetails = fs1.getKey().split("\\^");

                    // 获取过滤后的 faultSummary 中的 key
                    List<String> filteredFaultSummaryDetails = getFilteredFaultSummaryDetails(f1);

                    // 检查组1到组4是否完全匹配
                    boolean isMatchedGroup1to4 = true;
                    isMatchedGroup1to4 = matchExactGroups(filteredFaultSummaryDetails, faultSummaryDetails);


                    // 如果组1到组4匹配成功，继续检查组5到组8
                    boolean isMatchedGroup5to8 = false;
                    if (isMatchedGroup1to4) {
                        isMatchedGroup5to8 = matchGroups(filteredFaultSummaryDetails, faultSummaryDetails);
                    }


                    // 如果组1到组4完全匹配，且组5到组8有两个及以上相同的元素，或者组1到组4没有匹配，且组5到组8有两个及以上相同的元素，则认为是重复故障
                    if (isMatchedGroup1to4 && isMatchedGroup5to8) {
                        String flag = fs1.getFlag();
                        if (flag == null) {
                            flag = UUID.randomUUID().toString().substring(0, 6);  // 生成一个6位的UUID
                        }
                        // 设置isRepeat为1，表示重复故障
                        f1.setIsRepeat(1);

                        if (fs1.getIsRepeat() == 0) {
                            fs1.setIsRepeat(1);
                        }
                        f1.setFlag(flag);
                        fs1.setFlag(flag);
                        faultSummaryMapper.updateFaultSummary(fs1);
                    }
                }

            }
        }


//        for (FaultSummary f1 : faults) {
//            //生成finFlag uuid
//            String key = UUID.randomUUID().toString().substring(0,6);
//            for (FaultSummary fs1 : faults) {
//                if(f1 != fs1 && Objects.equals(f1.getNumber(), fs1.getNumber())) {
//                    if((Objects.equals(f1.getParentFlag(), fs1.getParentFlag()) && f1.getIsParent() == 1 && fs1.getIsParent() == 1) || (Objects.equals(f1.getFlag(), fs1.getFlag()) && f1.getIsRepeat() == 1 && fs1.getIsRepeat() == 1)) {
//                        if(f1.getFinFlag() != null && !StringUtils.isEmpty(f1.getFinFlag())) {
//                            fs1.setFinFlag(f1.getFinFlag());
//                        } else {
//                            f1.setFinFlag(key);
//                            fs1.setFinFlag(key);
//                        }
//
//                    }
//                }
//            }
//        }


        // 批量插入
        return faultSummaryMapper.insertFaultSummaryBatch(faults) > 0 ? 1:0;

    }


    // 精确匹配组的函数（组1到组4专用）
    private boolean matchExactGroups(List<String> filteredFaultSummaryDetails, String[] faultSummaryDetails) {
        // 提取组1到组4的部分
        List<String> group1To4Details = getGroupDetails(filteredFaultSummaryDetails, 1, 4);
        List<String> group1To4DetailsFs1 = getGroupDetails(Arrays.asList(faultSummaryDetails), 1, 4);

        // 先判断组四
        List<String> l1 = new ArrayList<>();
        List<String> l2 = new ArrayList<>();

        for (String s1 : group1To4Details) {
            // 加入X1
            if ("X1".equals(s1) && !l1.contains(s1)) {
                l1.add(s1);
            } else {
                // 加入组一
                String group = extractGroupNumber(s1);
                if ("1".equals(group) && !l1.contains(s1)) {
                    l1.add(s1);
                }

            }
        }

        for (String s1 : group1To4DetailsFs1) {
            // 加入X1
            if ("X1".equals(s1) && !l2.contains(s1)) {
                l2.add(s1);
            } else {
                // 加入组一
                String group = extractGroupNumber(s1);
                if ("1".equals(group) && !l2.contains(s1)) {
                    l2.add(s1);
                }

            }
        }
        // 都只有一个情况
        if (l1.size() == 1 && l2.size() == 1) {
            String s1 = l1.get(0);
            String s2 = l2.get(0);
            if (!s1.equals(s2)) {
                return false;
            }
        }

        // 如果l1的个数大于l2
        if (l1.size() > l2.size()) {
            int flag = 1;
            for (String s1 : l2) {
                if (l1.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }

        if (l1.size() < l2.size()) {
            int flag = 1;
            for (String s1 : l1) {
                if (l2.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }

        // 组四上面判断完了

        // 再判断组一
        List<String> l11 = new ArrayList<>();
        List<String> l22 = new ArrayList<>();

        for (String s1 : group1To4Details) {
            // 加入X2
            if ("X2".equals(s1) && !l11.contains(s1)) {
                l11.add(s1);
            } else {
                // 加入组二
                String group = extractGroupNumber(s1);
                if ("2".equals(group) && !l11.contains(s1)) {
                    l11.add(s1);
                }

            }
        }

        for (String s1 : group1To4DetailsFs1) {
            // 加入X2
            if ("X2".equals(s1) && !l22.contains(s1)) {
                l22.add(s1);
            } else {
                // 加入组二
                String group = extractGroupNumber(s1);
                if ("2".equals(group) && !l22.contains(s1)) {
                    l22.add(s1);
                }

            }
        }
        // 都只有一个情况
        if (l11.size() == 1 && l22.size() == 1) {
            String s1 = l11.get(0);
            String s2 = l22.get(0);
            if (!s1.equals(s2)) {
                return false;
            }
        }

        // 如果l11的个数大于l22
        if (l11.size() > l22.size()) {
            int flag = 1;
            for (String s1 : l22) {
                if (l11.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }

        if (l11.size() < l22.size()) {
            int flag = 1;
            for (String s1 : l11) {
                if (l22.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }


        // 组2到组3 存在两个以及两个以上相同即可
        List<String> all = new ArrayList<>();
        // all.add("X1");
        all.add("X3");
        all.add("X4");

        List<String> group1 = new ArrayList<>();
        List<String> group2 = new ArrayList<>();

        for (String s1 : group1To4Details) {
            // 表示X3之类的
            if (all.contains(s1) && !group1.contains(s1)) {
                group1.add(s1);
            } else {
                // 表示组
                String group = extractGroupNumber(s1);
                if (("3".equals(group) || "4".equals(group)) && !group1.contains(s1)) {
                    group1.add(s1);
                }
            }
        }


        for (String s1 : group1To4DetailsFs1) {
            // 表示X3之类的
            if (all.contains(s1) && !group2.contains(s1)) {
                group2.add(s1);
            } else {
                // 表示组
                String group = extractGroupNumber(s1);
                if (("3".equals(group) || "4".equals(group)) && !group2.contains(s1)) {
                    group2.add(s1);
                }
            }
        }

        // 不会出现这个情况  可以不删除
        /*if (group1.size() == 0 && group2.size() == 0) {
            return true;
        }*/

        int count = 0;
        if (group1.size() > group2.size()) {
            for (String s1 : group2) {
                if (group1.contains(s1)) {
                    count++;
                }
            }
        } else {
            for (String s1 : group1) {
                if (group2.contains(s1)) {
                    count++;
                }
            }
        }
        return count >= 1;
    }

    // 提取某些组的详情
    private List<String> getGroupDetails(List<String> details, int start, int end) {
        List<String> result = new ArrayList<>();
        for (String detail : details) {
            String group = extractGroupNumber(detail);
            int groupNumber = 0;
            if (!group.equals("")) {
                groupNumber = Integer.parseInt(group);
            }
            if (groupNumber >= start && groupNumber <= end) {
                result.add(detail);
            }
        }
        return result;
    }

    // 匹配部分组（适用于组6到组8，检查两个及以上相同元素）
    // 第一个参数是 当前数据的key的分割
    // 第二个参数  是查询出来的key
    private boolean matchGroups(List<String> filteredFaultSummaryDetails, String[] faultSummaryDetails) {

        // 先判断组6
        List<String> group1To4Details = getGroupDetails(filteredFaultSummaryDetails, 6, 8);
        List<String> group1To4DetailsFs1 = getGroupDetails(Arrays.asList(faultSummaryDetails), 6, 8);


        // 先判断组六
        List<String> l1 = new ArrayList<>();
        List<String> l2 = new ArrayList<>();

        for (String s1 : group1To4Details) {
            // 加入X6
            if ("X6".equals(s1) && !l1.contains(s1)) {
                l1.add(s1);
            } else {
                // 加入组六
                String group = extractGroupNumber(s1);
                if ("4".equals(group) && !l1.contains(s1)) {
                    l1.add(s1);
                }

            }
        }

        for (String s1 : group1To4DetailsFs1) {
            // 加入X6
            if ("X6".equals(s1) && !l2.contains(s1)) {
                l2.add(s1);
            } else {
                // 加入组六
                String group = extractGroupNumber(s1);
                if ("6".equals(group) && !l2.contains(s1)) {
                    l2.add(s1);
                }

            }
        }
        // 都只有一个情况
        if (l1.size() == 1 && l2.size() == 1) {
            String s1 = l1.get(0);
            String s2 = l2.get(0);
            if (!s1.equals(s2)) {
                return false;
            }
        }

        // 如果l1的个数大于l2
        if (l1.size() > l2.size()) {
            int flag = 1;
            for (String s1 : l2) {
                if (l1.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }

        if (l1.size() < l2.size()) {
            int flag = 1;
            for (String s1 : l1) {
                if (l2.contains(s1)) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                return false;
            }
        }

        // 组六上面判断完了

        // 下面判断组7与组8  存在一个以及一个以上相同即可
        List<String> all = new ArrayList<>();
        all.add("X7");
        all.add("X8");

        List<String> group1 = new ArrayList<>();
        List<String> group2 = new ArrayList<>();

        for (String s1 : group1To4Details) {
            // 表示X7之类的
            if (all.contains(s1) && !group1.contains(s1)) {
                group1.add(s1);
            } else {
                // 表示组7
                String group = extractGroupNumber(s1);
                if (("7".equals(group) || "8".equals(group)) && !group1.contains(s1)) {
                    group1.add(s1);
                }
            }
        }


        for (String s1 : group1To4DetailsFs1) {
            // 表示X7之类的
            if (all.contains(s1) && !group2.contains(s1)) {
                group2.add(s1);
            } else {
                // 表示组7
                String group = extractGroupNumber(s1);
                if (("7".equals(group) || "8".equals(group)) && !group2.contains(s1)) {
                    group2.add(s1);
                }
            }
        }

        // 不会出现这个情况  可以不删除
        /*if (group1.size() == 0 && group2.size() == 0) {
            return true;
        }*/

        int count = 0;
        if (group1.size() > group2.size()) {
            for (String s1 : group2) {
                if (group1.contains(s1)) {
                    count++;
                }
            }
        } else {
            for (String s1 : group1) {
                if (group2.contains(s1)) {
                    count++;
                }
            }
        }
        return count >= 1;

    }

    // 去重处理
    public static List<String> getDifference(List<String> listA, List<String> listB) {
        // 将列表 B 转换为集合，利用集合查找效率高的特性
        Set<String> setB = new HashSet<>(listB);
        // 用于存储列表 A 中独有的元素
        List<String> result = new ArrayList<>();

        // 遍历列表 A
        for (String element : listA) {
            // 如果元素不在集合 B 中，说明是列表 A 独有的元素
            if (!setB.contains(element)) {
                result.add(element);
            }
        }
        return result;
    }

    // 提取组号
    private String extractGroupNumber(String faultDetail) {
        // 假设组号的格式为 d717b组1，6d2bc组2，X3，X10，从字符串中提取数字
        // 提取组号部分的数字
        return faultDetail.replaceAll(".*(组|X)(\\d+)", "$2");
//        String[] parts = faultDetail.split("组");
//        return parts.length > 1 ? parts[1] : null;
    }

    // 获取 filteredFaultSummaryDetails 的方法
    private List<String> getFilteredFaultSummaryDetails(FaultSummary faultSummary) {
        // 将 faultSummary 的 key 按照 "-" 分割，并过滤掉 null 和 "X"
        return Arrays.stream(faultSummary.getKey().split("\\^"))
                .filter(Objects::nonNull) // 过滤 null 和 "X"
                .collect(Collectors.toList());
    }


    // 生成mu的所有父类
    public static List<String> process(FaultSummary mu) {
        List<String> parent = new ArrayList<>();
        String currentString = mu.getKey();
        boolean changed;
        do {
            changed = false;
            List<String> parts = new ArrayList<>(Arrays.asList(currentString.split("\\^")));
            int lastNonXIndex = -1;
            int currentGroup = -1;

            // 从后往前查找第一个非X项并提取组号
            for (int i = parts.size() - 1; i >= 0; i--) {
                String part = parts.get(i);
                if (!part.startsWith("X")) {
                    Matcher matcher = Pattern.compile("组(\\d+)$").matcher(part);
                    if (matcher.find()) {
                        currentGroup = Integer.parseInt(matcher.group(1));
                        lastNonXIndex = i;
                        break;
                    }
                }
            }

            if (lastNonXIndex == -1 || currentGroup == 1) {
                break; // 无处理项或遇到组1停止
            }

            // 收集所有当前组的非X项索引
            List<Integer> indicesToRemove = new ArrayList<>();
            for (int i = 0; i < parts.size(); i++) {
                String part = parts.get(i);
                if (!part.startsWith("X")) {
                    Matcher matcher = Pattern.compile("组(\\d+)$").matcher(part);
                    if (matcher.find() && Integer.parseInt(matcher.group(1)) == currentGroup) {
                        indicesToRemove.add(i);
                    }
                }
            }

            if (indicesToRemove.isEmpty()) {
                continue;
            }

            int maxIndex = Collections.max(indicesToRemove);

            // 构建保留元素列表及其原索引
            List<String> retainedParts = new ArrayList<>();
            List<Integer> retainedIndices = new ArrayList<>();
            for (int i = 0; i < parts.size(); i++) {
                if (!indicesToRemove.contains(i)) {
                    retainedParts.add(parts.get(i));
                    retainedIndices.add(i);
                }
            }

            // 确定插入位置
            int insertPos = retainedParts.size();
            for (int i = 0; i < retainedIndices.size(); i++) {
                if (retainedIndices.get(i) > maxIndex) {
                    insertPos = i;
                    break;
                }
            }

            // 插入X组号
            retainedParts.add(insertPos, "X" + currentGroup);
            // 他的父类
            currentString = String.join("^", retainedParts);
            // 看是否相同或者是否是父类

            if(!"X1^X2^X3^X4^X5^X6^X7^X8^X9^X10".equals(currentString) && !parent.contains(currentString)) {
                parent.add(currentString);
            }
            // System.out.println(currentString);
            changed = true;
        } while (changed);
        return parent;
    }
}
